package main

import (
	"fmt"
	"math/rand"
	"time"
)

type User struct {
	Name  string
	Phone string
}

//模拟用户列表
var userList = make([]User, 0)

//用户列表初始化
func init() {
	userList = append(userList, User{
		Name:  "刘备",
		Phone: "18888888888",
	}, User{
		Name:  "关羽",
		Phone: "17777777777",
	}, User{
		Name:  "张飞",
		Phone: "1999999999",
	})
}

func main() {
	messagesQueue := make(chan User, 10)
	done := make(chan bool)

	defer close(messagesQueue)
	//创建10个线程，模拟10个短信的发送者（消费者），竞争通道的用户资源
	for i := 0; i < 10; i++ {

		go func(v int) {
			ticker := time.NewTicker(1 * time.Second)
			for range ticker.C {
				select {
				case <-done:
					fmt.Println("已结束")
					return
				default:
					f := <-messagesQueue
					sendSmsCode(f, v)
				}
			}

		}(i)

	}

	//生产者 每秒生成一个等待发送短信的用户资源
	go func() {
		ticker := time.NewTicker(1 * time.Second)
		for range ticker.C {
			u := userList[rand.Intn(3)]
			fmt.Printf("用户%s发送短信\n", u.Name)
			messagesQueue <- u
		}
	}()

	//主线程等待15s后close done
	time.Sleep(15 * time.Second)
	close(done)

}

//模拟发送短信业务
func sendSmsCode(user User, id int) {
	rand.Seed(time.Now().UnixNano())
	//生成非严谨的短信验证码
	code := rand.Intn(10000)
	//打印发送日志
	fmt.Printf("模拟携程ID:%d,用户:%s,手机号为:%s,发送验证码:%d\n", id, user.Name, user.Phone, code)

}
